const jwt = require('jsonwebtoken');
const secretKey = 'e8104f615ae4c869415b902w8x51d93cd70f9a86d3818eb279';

const main = {
  generate: (id) => {
    const token = jwt.sign({ id }, secretKey, { expiresIn: '0.5h' });
    return token;
  },

  validate: (req, res = null) => {
    const token = req.headers['authorization'];
    if (!token) {
      if(res) res.send({ code: 400, err: '无效的身份信息' });
      return 0;
    } try {
      const decoded = jwt.verify(token, secretKey);
      return decoded.id;
    } catch (err) {
      if (err.name === 'TokenExpiredError') {
        if(res) res.send({ code: 401, err: '登录超时' });
        return -1;
      }
      if(res) res.send({ code: 400, err: '无效的身份信息' });
      return 0;
    }
  }
}

module.exports = main;